/**
 * async函数实现基本原理：generator+自执行器
 */

function fn(args) {
  return spawn(function* () {
    yield 1;
    yield 2;
    yield 3;
    return "hello";
  });
}

function spawn(genF) {
  console.log(11);
  return new Promise((resolve, reject) => {
    const gen = genF();

    function step(nextF) {
      let next;
      try {
        next = nextF();
      } catch (e) {
        return reject(e);
      }

      if (next.done) return resolve(next.value);
      Promise.resolve(next.value).then(
        v => {
          step(() => gen.next(v));
        },
        e => {
          step(() => gen.throw(e));
        }
      );
    }

    step(() => gen.next(undefined));
  });
}

// 测试
fn(2).then(v => {
  console.log(v);
});
